import {
  request
} from "../../request";
import {regeneratorRuntime} from "../../libs/runtime/runtime";
//引入第三方表单审核插件
import WxValidate from '../../utils/WxValidate.js'
Page({
  data: {
    //上传图片展示地址
    formData:{
      img1: '',
      img2: '',
      img3: '',
      img4:'',
      img5:'',
      img6:'',
      shop_addr: '',
      shop_jwd: '',
      shop_name: '',
      shop_tel: '',
    },
    //页面图片展示
    Imgs: {
      img1: '',
      img2: '',
      img3: '',
      img4:'',
      img5:'',
      img6:''
    },
    //页面基本信息展示数据
    exampleImgs:{
      img1: ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.wdjl.net%2Fuploads%2Fallimg%2F200415%2F15-200415125923.jpg&refer=http%3A%2F%2Fwww.wdjl.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623746841&t=d51d13af0c309eef7d1cf1692cf7ab69','门脸图','需包含完整牌面'],
      img2: ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp0.meituan.net%2Fdeal%2F__30185921__2659464.jpg&refer=http%3A%2F%2Fp0.meituan.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623746941&t=8d96c7d152a1ab25d97609bb169f44ba','店内环境图','拍摄店内真实环境'],
      img3: ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp0.meituan.net%2Fdeal%2F__30185921__2659464.jpg&refer=http%3A%2F%2Fp0.meituan.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623746941&t=8d96c7d152a1ab25d97609bb169f44ba','logo','需使用真实店铺logo'],
      img4: ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp0.meituan.net%2Fdeal%2F__30185921__2659464.jpg&refer=http%3A%2F%2Fp0.meituan.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623746941&t=8d96c7d152a1ab25d97609bb169f44ba','身份证','请上传带有人像图片的身份证'],
      img5: ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp0.meituan.net%2Fdeal%2F__30185921__2659464.jpg&refer=http%3A%2F%2Fp0.meituan.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623746941&t=8d96c7d152a1ab25d97609bb169f44ba','运营许可','需使用真实运营许可'],
      img6: ['https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fp0.meituan.net%2Fdeal%2F__30185921__2659464.jpg&refer=http%3A%2F%2Fp0.meituan.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623746941&t=8d96c7d152a1ab25d97609bb169f44ba','食品安全','食品安全资格证']
    },
    //选择的图片数组
    chooseImgs: [],
    //选择的地址&经纬度
    shop_addr:'',
    shop_jwd:'',
    ondisplay: 'none'
  },
  //上传的图片路径
  UpLoadImgs: [],
  onLoad:function(options){
    this.sX();
    let {formData}= this.data
    formData = {...formData,...options}
    this.setData({
      formData
    })
    console.log(this.data.formData)
    this.initValidate() //验证规则函数
  },
  //输入电话
  InputShop_tel: function(e){
    let {formData} = this.data
    formData.shop_tel = e.detail.value;
    this.setData({
      formData
    })
  },
  //输入店铺名称
  InputShop_name:function(e){
    let {formData} = this.data
    formData.shop_name = e.detail.value;
    this.setData({
      formData
    })
  },
  //表单提交按钮
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    const params = e.detail.value
    //校验表单数据
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    let {formData} = this.data
    this.setData({
      formData:{...formData,...e.detail.value}
    })
    //上传图片到外网 路径存储在this.UpLoadImgs
    this.handleImgSubmit()
  },
  //表单重置按钮
  formReset: function () {
    console.log('form发生了reset事件')
    this.setData({
      formData: ''
    })
  },
  //点击输入地址
  onChangeAddress: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        let {formData} = that.data
        let address = {
          shop_addr: res.name,
          shop_jwd:res.latitude + ',' + res.longitude,
        }
        that.setData({
          formData:{...formData,...address}
        });
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },
  //点击加号选择图片 中间为图片审核
  handleChooseImg(e) {
    console.log(e.currentTarget.dataset.index)
    console.log(this.data.Imgs)
    let key = e.currentTarget.dataset.index
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (result) => {
        let that = this
        console.log(result.tempFilePaths[0])
        //审核检验代码
        wx.showLoading({
          title: '图片核验中',
          mask: true
        })
        wx.uploadFile({  
          url: 'https://fourgoldhua.cn/shop_sc/imgCheck',  
          filePath: result.tempFilePaths[0],  
          name: 'file',
          header: {
            'content-type': 'mulipart/form-data',
            'accept': 'application/json'
          },
          formData: {
            
          },  
          //upload被微信封装好加不了fail的处理
          success: function (res) {  
            wx.hideLoading();
            if(!res.data){
              wx.showToast({
                title: '图片违规',
              })
              return 
            }
            else{
              console.log("图片核验成功")
              let Imgs = that.data.Imgs
              Imgs[key] = result.tempFilePaths
              that.setData({
                Imgs
              })
            } 
          }  
        }) 
      },
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  //点击图片删除
  handleRemoveImg(e) {
    const {
      index
    } = e.currentTarget.dataset;
    let {
      Imgs
    } = this.data
    Imgs[index][0]='';
    this.setData({
      Imgs
    })
  },
  //图片上传前检验合法并提示信息
  handleImgSubmit() {
    const {
      Imgs,
      chooseImgs
    } = this.data
    for (let key in Imgs) {
      // console.log(key)
      // console.log(Imgs[key][0])
      let v = Imgs[key][0]
      if (v == undefined) {
        wx.showModal({
          content: `请上传${this.data.exampleImgs[key][1]}`,
          showCancel: false,
        })
        return
      }
      chooseImgs.push(Imgs[key][0])
    }
    this.setData({
      chooseImgs
    })
    this.ImgUpload();
  },
  //图片上传函数
  ImgUpload:function(){
    let {chooseImgs,formData} = this.data
    let UpLoadImgs = this.UpLoadImgs
    let that = this
    chooseImgs.forEach((v,i)=>{
      wx.uploadFile({  
        url: 'https://fourgoldhua.cn/shop_sc/upload',  
        filePath: v,  
        name: 'file',
        header: {
          'accept': 'application/json',
          'token':`${wx.getStorageSync('openid')}`
        },
        formData: {
         formData
        },  
        success: function (res) {
          console.log(res.data)
          UpLoadImgs.push({
            [`img${i+1}`]:res.data
          })
          if(UpLoadImgs.length==chooseImgs.length){
            console.log("图片上传成功")
            //上传图片完毕以后上传表单数据 完全是因为后端的问题
            console.log(UpLoadImgs)
            that.uploadfromdata(UpLoadImgs)
          }
        }  
      }) 
    })
  },
  //上传formdata 数据 因为后端的废物
  uploadfromdata:function(UpLoadImgs){
    let {formData} = this.data
    for (const a of UpLoadImgs) {
      let data = {...formData,...a}
      formData = data;
    }
    this.uploadfromdata1(formData)
  },
  //上传formdata 数据
  async uploadfromdata1(formData) {
    console.log(formData)
    const res = await request({
      url: '/shop_sc/ruzhu',
      method:'POST',
      data:{
        formData
      }
    });
    console.log(res)
    if(!res){
      wx.showToast({
        title: '上传失败',
      })
    } else {
      wx.showToast({
        title: '上传成功',
      })
      setTimeout((n) => {
        wx.switchTab({
          url: '/pages/mine/mine',
        })
      },500)
    }
  },
  //表单报错提示 
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //表单验证函数
  initValidate() {
    const rules = {
      shop_name: {
        required: true,
        maxlength: 15
      },
      shop_tel:{
        tel: true,
      },
      shop_addr: {
        required: true,
      }
    }
    const messages = {
      shop_name: {
        required: "请填写店铺名称",
        maxlength:"最多可以输入15个字符的店铺名称"
      },
      shop_tel:{
        tel: "请输入11位的手机号码",
      },
      shop_addr: {
        required: "请选择店面地址",
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  async sX() {
    const res = await request({
      url: '/shuju/sx',
    });
    if(res.data === 1){
      this.setData({
        ondisplay: 'block'
      })
    }
  },
})